package common.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

public class ImgBase64Utils {


	/**
	 * 
	 * 将前台图片信息转换为文件保存
	 * 
	 * @param dir
	 *            保存的根目录
	 * @param filePath
	 *            文件路径前缀
	 * @param imgData
	 *            图片数据
	 * @return 保存的文件名称
	 * @throws IOException
	 */
	public static String base64StringToImage(File dir, String filePath, String imgData) throws IOException {
		// 使用正则表达式，排除img标签src属性值已经是base64编码的情况
		Pattern pattern = Pattern.compile("^data:image/(png|gif|jpg|jpeg|bmp|tif|psd|ICO);base64,.*");
		Matcher matcher = pattern.matcher(imgData);
		if (!matcher.matches()) {
			return null;
		}
		String type = matcher.group(1);
		String fileName = UUIDUtil.createUuid() + "." + type;
		String imgDate = imgData.substring(imgData.indexOf(",") + 1);
		File parent = new File(dir, filePath);
		if (!parent.exists()) {
			parent.mkdirs();
		}
		byte[] bytes1 = Base64.getDecoder().decode(imgDate);
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
		BufferedImage bi1 = ImageIO.read(bais);
		File w2 = new File(parent, fileName);
		ImageIO.write(bi1, type, w2);
		return fileName;
	}
//  public static String data = "";
//	public static void main(String[] args) throws IOException {
//		File dir = new File("/test");
//		System.out.println(base64StringToImage(dir, "/abc/img", data));
//	}

}
